/**
 * Created by seeker910 on 2022/4/22.
 * @description markdown 文件编辑器
 */
Rsd.define('Rsd.tool.MarkdownEditor', {
    extend: 'Rsd.container.Dialog',
    requires: [
        'Rsd.form.Button',
        'Rsd.form.TipButton',
        'Rsd.form.Label',
        'Rsd.form.Link',
        'Rsd.form.CheckBox', 
        'Rsd.control.Svg',
        'Rsd.control.IframeBox',
        'Rsd.control.List',
        'Rsd.control.HtmlBox'
    ],
    //
    editorHeight: '100%',
    /**
     * 是否显示目录栏
     */
    showIndex: true,
    //
    markdownSvg:{
        viewBox:"0 0 1024 1024",
        paths:[
            {
                d: "M193.3312 398.1312h637.3376l90.9312 90.9312v250.2656H102.4v-250.2656l90.9312-90.9312z m0 0",
                fill: "#719bb0"
            },
            {
                d: "M739.7376 921.6H284.2624c-24.1664 0-47.104-9.4208-64.3072-26.624-17.2032-17.2032-26.624-40.1408-26.624-64.3072V193.3312c0-24.1664 9.4208-47.104 26.624-64.3072 17.2032-17.2032 40.1408-26.624 64.3072-26.624h364.1344l181.8624 181.8624v545.9968c0 24.1664-9.4208 47.104-26.624 64.3072-16.7936 17.6128-40.1408 27.0336-63.8976 27.0336z m0 0",
                fill: "#EEF1FF"
            },
            {
                d: "M102.4 489.0624h819.2v273.2032H102.4z",
                fill: "#1688c4"
            },
            { 
                d: "M648.3968 102.4l181.8624 181.8624h-90.9312c-24.1664 0-47.104-9.4208-64.3072-26.624-17.2032-17.2032-26.624-40.1408-26.624-64.3072V102.4z m0 0", 
                fill:"#C4C8D9" 
            },
            {
                d: "M418.2016 671.744L360.448 527.9744l-0.4096-0.4096H315.392v196.608h36.0448V610.304l-1.2288-21.2992 54.4768 134.3488 0.4096 0.8192h26.624l54.8864-137.216-1.6384 22.528v114.688h36.4544v-196.608h-43.8272zM613.5808 527.5648h-61.8496v196.608h65.9456c29.0816 0 51.6096-7.3728 66.3552-22.528 16.384-16.384 24.576-41.7792 24.1664-75.3664-0.8192-64.3072-32.768-97.4848-94.6176-98.7136z m2.8672 165.4784h-28.672v-132.7104h27.4432c38.912 0 57.7536 21.7088 57.7536 65.9456 0.4096 24.576-4.9152 42.5984-15.9744 53.6576-9.0112 8.6016-21.2992 13.1072-37.6832 13.1072h-2.8672z",
                fill: "#FFFFFF"
            }
        ]
    }, 
    addSvg:{
        viewBox:"0 0 1024 1024",
        paths:[
            { 
                d:"M608 64v160c0 52.2 41.672 94.672 93.56 95.968L704 320h160v576a64 64 0 0 1-62 63.968L800 960H224a64 64 0 0 1-63.968-62L160 896V128a64 64 0 0 1 62-63.968L224 64h384zM512 400a32 32 0 0 0-32 32v111.992L368 544a32 32 0 1 0 0 64l111.992-0.008L480 720a32 32 0 1 0 64 0l-0.008-112.008L656 608a32 32 0 1 0 0-64l-112-0.008V432a32 32 0 0 0-32-32zM672 69.752a63.984 63.984 0 0 1 17 11.312l1.544 1.488L832 223.992l13.256 13.264A63.984 63.984 0 0 1 858.24 256H704a32 32 0 0 1-31.96-30.4L672 224V69.752z",
                fill:"#1688c4"
            }]
    },
    /**
     * 
     */
    layout: 'hbox',
    /**
     * 
     */
    items: [
        {
            xtype: 'list',
            usingItemHover:true, 
            label: {
                xtype: 'link',
                text: '[刷 新]',
                width: '100%',
                height: '40px',
                margin: '3px 0 3px 0',
                label: {
                    width: 80,
                    content: '页面列表',
                    align: 'center',
                    style: {
                        color: '#000',
                        cursor: 'default',
                        textAlign: 'left',
                        //fontWeight:'Bold',
                        fontSize: '130%',
                        borderBottom: '1px darkgrey dotted'
                    }
                },
                ctrl: {
                    style: {
                        //element:'ctrl', 
                        color: '#fff',
                        backgroundColor: '#b92525f0',
                        cursor: 'pointer',
                        lineHeight: '40px',
                        borderRadius: '4px'
                    }
                }

            }, 
            width: 160,
            height: '100%',
            itemXtype: 'svg',
            itemKeyMember: 'key',
            itemClick: 'pageIndexChanged',
            itemStyle:{
                width:'90%',
                height:80
            },
            layout: {type:'none',align:'center',content:'start center'},
            dataSource: null

        },
        {
            xtype: 'iframe',
            flex: 1, 
            height: '100%',
            src: 'javascript:void(0)',
            ctrl: { style: { boder: '1px red solid' } },
            onload: 'iframe_load',
            label: {
                position: 'top',
                space: 0,
                xtype: 'container',
                header: false,
                height: 60,
                style: { lineHeight: 60 ,display:'flex', alignItems: 'center'},
                items: [ 
                     {
                        xtype: 'checkbox',
                        margin: '0 0 0 20',
                        width: 120,
                        height: 30,
                        checked: true, 
                        label: {
                            position: 'right',
                            width: 90,
                            content: '自动保存',
                            style: { color: '#000', fontSize: '120%' }
                        },
                        tip: '勾选后,每5分钟自动保存',
                        onchange: 'on_checked'
                    }, 
                    {
                        xtype: 'tip-button',
                        text: '按 ctrl+s 保存文件',
                        style: { color: '#000', fontSize: '120%' },
                        height: 25,
                        width: 25,
                    }, 
                     {
                        flex:1
                    },
                      {
                        xtype: 'label',
                        label: '上次保存时间：',
                        style: { color: '#999289', textAlign: 'left' },
                        height: 40,
                        width: 250,
                    }, 
                     {
                        xtype: 'button',
                        height: 40,
                        width: 120,
                        margin: '0 20 0 0',
                        style: { 
                            backgroundColor: '#0c08e4bd'
                        },
                        text: '保存文件(S)',
                        handler: 'btn_save'
                    },  
                    {
                        xtype: 'button',
                        height: 40,
                        width: 100,
                        margin: '0 10 0 0',
                        style: { 
                            backgroundColor: '#034e09bd'
                        },
                        text: '预 览',
                        handler: 'btn_preview'
                    },
                    {
                        xtype: 'button',
                        height: 40,
                        width: 100,
                        margin: '0 10 0 0',
                        style: { 
                            backgroundColor: '#910207ff'
                        },
                        text: '退 出',
                        handler: 'btn_close'
                    }
                ]
            },
            handleMessage:'handleMessage'
            
        }
    ], 
    /**
     * @description string or object 文档信息 ;string md字符串，object: { Id: null, Key: null, Name: '' },
     */
    data:"正在加载, 请稍后...",
    /**
     * 插件位置
     * /plugin/editormd/app/edit.html
     */
    src:null,
    /**
     * API标准接口，集成该组件的服务端标准API
     */
    services:{
        /**
        * 文档索引编辑函数
        */
        newIndex: '',
        /**
         * 文档索引加载函数
         */
        getIndex: '',
        /**
         * 文件下载服务名称
         */
        downloadFile: '',
        /**
         * 上传
         */
        uploadFile: '',
    },
    /**
     * 
     * @param {*} config 
     */
    constructor: function MarkdownEditor(config) {

        config = config || {};
        this.apply(config);
        var me = this;

        //设置编辑控件页面地址
        var _plugin_src = this.src || (Rsd.getRedjsHost()+'/plugin/editormd/app/editor.html?h=' + me.editorHeight)
        me.items[1].src =  _plugin_src;

        if (!this.showIndex) {
            this.items[0].hidden = true;
        }
        //
        if(this.showIndex)
        {
            this.items[0].label.handler = function () {
                me.loadIndex();
            };
        }
        
        
    },
    /** 
     * 
     */
    load: function load() {
        this.callParent(); 
        //默认文档 
        if(this.mdContent)
        {
             this.renderMdFile(this.mdContent);
        }
        var _token = Rsd.getAppToken();
        if(_token)
        {
            this.__interval_id = setInterval(function(){ 
                Rsd.app.checkSession(_token);
            },20*60*1000);
        } 
        
    },
    /**
     * 
     */
    onClose:function onClose()
    {
        if(this.__interval_id)
        { 
            clearInterval(this.__interval_id);
        }
        this.callParent();
    },
    /**
     * 处理 来自iframe的消息，如：页面状态
     * @param {*} data 
     * @param {*} origin 
     */
    handleMessage:function handleMessage(data,origin)
    {
        // 验证消息来源
        if (origin !== 'http://global.sellerpartner.cn') { 
            //return;
        } 
        console.error('Received message from iframe:', data);
    },
    /**
     * 
     */
    loadIndex: function loadIndex() {
        var me = this;
  
        me.loadDocPages(function (indexList) {

            for (var i in indexList) {
                var item = indexList[i];
                if (item.key) {
                    item.style = item.style || {overflow: 'hidden' };
                    if(me.currentPage && me.currentPage.key == item.key)
                    {
                        item.label.style = item.label.style || {};
                        item.label.style.fontWeight='bold';
                    }
                    //章节 页面加载 
                    item.handler = function () {
                        //console.log('here is me ', this.data);
                        me.selectPage(this.data);
                    };
                }

            }

            me.items[0].loadData(indexList);
        });
    },
    /**
    * @description 获取文件页面列表
    * @param {*} row 
    * @param {*} callback 
    */
    loadDocPages: function loadDocPages(callback) {
        var me = this;
        
        if(!Rsd.isObject(this.data))
        {
            me.error('data is not object type');
            console.log(this.data);
            return;
        }
        var docId = me.data.Id;
        var docKey = me.data.Key;
        var docName = me.data.Name;

        var list = [
            { 
                xtype:'label',
                label:'O',
                mulitiLine:true,
                key: docKey,
                width: '100%', 
                height:50,
                style:{
                    textAlign:'center',
                    fontSize:'120%',
                    fontWeight: 900,
                    color: '#000'
                }, 
                text:docName,  
                data: me.data 
            },
            { 
                key: docKey,
                width: '100%', 
                height:70,
                label:{
                    content:'首 页',
                    position:'bottom',
                    space:0,
                    height:30,
                    style:{
                        fontWeight:me.currentPage ?"unset":"bold"
                    }
                },
                dataSource:me.markdownSvg,
                tip: me.data.Description,  
                data: me.data 
            }];
       
        //获取索引
        Rsd.app.requestService(me.services.getIndex, me.data, function (resp) {

            if (resp.success) {
                for (var i in resp.data) {
                    var no = Number(i) + 1;
                    //{text:'第一章：xxxxxxxx',width:'100%',handler:function(){alert(this.text);}},
                    list.push({
                        key: resp.data[i].Key,
                        width: '100%', 
                        height:70,
                        label:{content:resp.data[i].Title,position:'bottom',space:0,height:30},  
                        dataSource:me.markdownSvg,
                        data: resp.data[i],
                        tip: resp.data[i].Title + ':' + resp.data[i].Description
                    });
                }

            }

            list.push({
                width: '100%',
                height: 70,
                label: { content: '添加新页面', position: 'bottom', space: 0, height: 30 },
                style: {
                    element: 'ctrl',
                    textDecoration: 'underline',
                    textAlign: 'right',
                    //fontWeight:'Bold', 
                    //backgroundColor: '#03127eb5',
                    color: '#f70000d9'
                }, 
                dataSource: me.addSvg,
                handler: function () {

                    Rsd.create('Rsd.zen.dialog.FormDialog', {
                        style: { maxHeight: '100%' },
                        docKey: docKey,
                        readonly: false,
                        height: 280,
                        width: 500,
                        delayShow: 50,
                        header: { content: '添加新页面' },
                        style: { borderRadius: 0, maxHeight: '100%' },
                        formFields: [
                            {
                                xtype: 'text',
                                label: '标题',
                                dataIndex:'title',
                                required:true,
                                width: '80%'
                            },
                            {
                                xtype: 'text',
                                label: '描述',
                                dataIndex:'description',
                                 required:true,
                                width: '80%'
                            },
                            {
                                xtype: 'text',
                                label: '索引编码',
                                dataIndex:'indexCode',
                                required:true,
                                width: '80%'
                            }
                        ],
                        labelWidth: 100,
                        buttons: ['save', 'delete'],
                        saveHandler: function (data) {
                            var dialog = this;
                            //
                            data['key'] = me.data.Key; 
                            data['sortIndex'] = 0;
                            Rsd.requestService(me.services.newIndex,data,function(resp){
                                if(resp.success)
                                {
                                    dialog.close();
                                    me.loadIndex();
                                }
                            });
                            //alert('暂未实现保存功能：'+me.services.newIndex);
                        },
                        afterNewHandler: function (newObj) {
                            me.loadDocPages(callback);
                        }
                    }).showDialog();

                }
            });

            callback(list);
        });
    },
    /**
     * 
     * @param {*} page 
     */
    selectPage: function selectPage(page) {
        var me = this;
 
        var _fn_relocate = function () {

            me.download(page);
        }

        var c_win = me.items[1].ctrl.element.contentWindow;

        var _fn = function () {

            if (c_win && c_win.mdEditor && c_win.mdEditor.isChanged) {

                Rsd.showMessage('文档已修改，是否保存？', [
                    {
                        text: '保 存',
                        fn: function () { me.upload(false, _fn_relocate); }
                    },
                    { text: '不保存', fn: _fn_relocate }
                ]);
            }
            else {
                _fn_relocate();
            }
        }

        if (c_win) {
            _fn();
        }
        else {
            var _id = setInterval(function () {

                c_win = me.items[1].ctrl.element.contentWindow;
                if (c_win) {
                    clearInterval(_id);
                    _fn();
                }

            }, 100);
        }

        //
    },
    /**
     * 
     * @param {*} page 
     */
    download: function download(page) {
        if(Rsd.isEmpty(this.services.downloadFile))
        {
            alert('未设置下载服务');
            return;
        }
        if (Rsd.isEmpty(page)) {
            return;
        } 
        var me = this;
        
        Rsd.app.requestService(this.services.downloadFile, page, function (resp) {

            if (!resp.success) {
                return;
            }
            //更新当前page
            me.page = page;

            //清除自动保存
            if (me.__interval_id) {
                window.clearInterval(me.__interval_id);
            }

            me.renderMdFile(resp.data||('# ' + (page.Title||'请输入内容')), function () {
                //在成功渲染后 开启自动保存 ,如果 放在在未加载前 触发保存 污染数据
                me.__interval_id = setInterval(function () { me.upload(true, null); }, 5 * 1000 * 60);
            });

            //此方案 仅在 解决跨域问题的情况下可用。
            var c_win = me.items[1].ctrl.element.contentWindow;

            //绑定预览事件
            if (me.items[1].label
                && me.items[1].label.content
                && c_win.bindPreviewEvent) {
                c_win.bindPreviewEvent(function (isPreview) {
                    var btn = me.items[1].label.content.items[6].ctrl.element;
                    btn.innerHTML = isPreview ? '关闭预览' : '预 览';
                });
            }
            //设置保存方法
            if (c_win.bindSaveFunction) {
                c_win.bindSaveFunction(function () { me.upload(false, null); });
            }

        });


    },
    /**
     * 上传文件
     * @param {*} autoSave 是否是自动保存
     * @param {*} callback 保存后回调方法
    */
    upload: function upload(autoSave, callback) {
         if(Rsd.isEmpty(this.services.uploadFile))
        {
            alert('未设置上传服务');
            return;
        }
        var me = this;
        var page = me.page;
        if (Rsd.isEmpty(page)) {
            Rsd.alert('无法保存文件。');
            return;
        }
        if (!me.items[1]) {
            window.clearInterval(me.__interval_id);
            return;
        }
        
        var code = me.getMdFileCode();
       
        var c_win = me.items[1].ctrl.element.contentWindow;
        var file =  top.Rsd.stringToFile(code,'text/x-markdown',  page.Key + '.md');
        var data = Rsd.apply({},page); 
        data['file'] = file;
        data['desc'] = '这是来自SellerPartner的MD文件内容';
        //console.log(data);
        top.Rsd.postFile(me.services.uploadFile,data,function(resp){
            //console.log('post file :' ,resp);

            if (resp.success) {
                if (autoSave) {
                    Rsd.popup('已自动保存');
                }
                else {
                    Rsd.popup('保存成功');
                }

                var time = Rsd.formatTimestamp(Date.now(), "yyyy-MM-dd hh:mm:ss");
                c_win.mdEditor.changeTime = time;
                c_win.mdEditor.isChanged = false;
                //更新 页面提示时间
                me.items[1].label.content.items[3].setValue(time);
                if (callback) {
                    callback();
                }
            }

        });
        
  
    },
    /**
     * 
     * @returns 
     */
    getMdFileCode:function getMdFileCode()
    {
        var me = this;
        //此方案 仅在 解决跨域问题的情况下可用。
        //替代方法是，通过postMessage 来传递 获取和加载 md 文档内容
        var c_win = me.items[1].ctrl.element.contentWindow;
        return  c_win.mdEditor.getMarkdown();
    },
    /**
     * 
     * @param {*} listItem 
     */
    pageIndexChanged: function pageIndexChanged(listItem,evt,config) {
      
        //console.log(arguments);
        if(this.currentPageNode)
        {
            this.currentPageNode.label.element.style.fontWeight='unset';
        }
       
        if (listItem.data && listItem.data != this.page) {
            this.selectPage(listItem.data);
            listItem.label.element.style.fontWeight='bold';
            this.currentPageNode =  listItem;
            this.currentPage = config;
            //阻止事件 向下传递
            evt.stopPropagation();
        }
        //事件向下层传递
    },
    /**
     * 
     * @param {*} evt 
     * @returns 
     */
    iframe_load: function iframe_load(evt) {
        var me = this;
       
        //console.log('iframe_load',evt.target.src , me.items[1].src);
        if (evt.target.src !== me.items[1].src) {
           // return;
        }
        var c_win = me.items[1].ctrl.element.contentWindow;
        //console.log(c_win);
        if (c_win.document.readyState !== "complete") {
            return;
        }
       //加载文档目录
        if(this.showIndex)
        {
            //目录信息
            me.loadIndex();
        }

        if (Rsd.isString(me.data)) {
            me.renderMdFile(me.data, null);
            return;
        }
        
        if (Rsd.isObject(me.data)) {
            //
            me.selectPage(me.data); 
            return;
        }
        
    },
    /**
     * 
     * @param {*} data 
     * @param {*} callback 
     * @returns 
     */
    renderMdFile: function renderMdFile(data, callback) {

        //console.log('renderMdFile',data);
       
        var me = this;
        var c_win = me.items[1].ctrl.element.contentWindow;
       
        if(c_win.location.href =="about:blank")
        {
            return;
        }
       
        if (c_win.render) {

            setTimeout(function(){
                c_win.render(data, callback);
            },100);
            
            return;
        }

        c_win.onload =function(){

            if (c_win.render) {

                setTimeout(function(){
                    c_win.render(data, callback);
                },100);
                
                return;
            }
            //console.log(c_win)
            console.error(c_win.location.href + "未实现接口:render");
        };
        
    },
    /**
     *  
     */
    on_checked: function (sender, evt) {
        var me = this;
        if (sender.isChecked()) {
            clearInterval(me.__interval_id);
            me.__interval_id = setInterval(function () { me.upload(true, null); }, 5 * 1000 * 60);
            Rsd.popup('自动保存已开启');
        }
        else {
            clearInterval(me.__interval_id);
            Rsd.popup('自动保存已关闭');
        }
    },
    /**
     * 
     */
    btn_save: function btn_save() {
        this.upload(false, null);
    },
    /**
     * 
     */
    btn_preview: function btn_preview() {
        var me = this;
        var c_win = me.items[1].ctrl.element.contentWindow;
        if(!c_win.mdEditor)
        {
            Rsd.popup('编辑器初始化失败，无法预览');
            return;
        }
        var html = c_win.mdEditor.getHTML();
        Rsd.create('Rsd.container.Dialog',{
            header:{
                content:'【预览】' +  (me.page&&me.page.Title)||'临时文档', 
                style:{backgroundColor:'#fff'}
            } ,
            width: 800,
            height: '100%',
            layout:'fit',
            style:{backgroundColor:'#fff'},
            items: [
                {
                    xtype:'html-box',
                    width:'100%',
                    height: '100%', 
                    style:{backgroundColor:'#fff'},
                    html: html,
                }
            ] 
        }).showDialog();
    },
    /**
     * 
     */
   btn_close:function btn_close()
   {
        var me = this;
        me.close();
   },
    /**
     * 
     */
    beforeClose: function beforeClose() {
        var me = this;
        if (me.closeWithoutSaving === true) {
            delete me.closeWithoutSaving;
            return;
        }
        //通过dialog.closeCancel 进行关闭拦截： 如果修改后未保存，阻止窗体关闭
        var c_win = me.items[1].ctrl.element.contentWindow;
        if(!c_win.mdEditor)
        {
            Rsd.popup('编辑器初始化失败，无法预览');
            return;
        }

        me.closeCancel = c_win && c_win.mdEditor && c_win.mdEditor.isChanged;

        if (me.closeCancel) {
            Rsd.showMessage('文档已修改，是否保存？', [
                {
                    text: '保存并关闭',
                    width: 85,
                    height: 32,
                    style: {
                        element: 'ctrl',
                        color: '#fff',
                        backgroundColor: '#1744a9bd'
                    },
                    fn: function () {
                        me.upload(false, function () { me.close(); });
                    }
                },
                {
                    text: '关闭(不保存)',
                    width: 95,
                    height: 32,
                    style: {
                        element: 'ctrl',
                        color: '#fff',
                        backgroundColor: '#9a1204e6'
                    },
                    fn: function () {
                        me.closeWithoutSaving = true;
                        me.closeCancel = false;
                        me.close();

                    }
                },
                {
                    text: '取消(继续编辑)',
                    width: 105,
                    height: 32,
                }
            ]);
        }
    }

}, function (type) {



});